package d4l.ui;



import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.text.*;


public class Runner extends JPanel {

    private String [] teachingMethods = new String [] {
            "Lecture", "Seminar", "Print"
    };

    private int targetHours = 30;

    private JLabel totalLabel;

    private JLabel targetLabel;

    private JTextField [] hourFields;

    private DocumentFilter filter = new DocumentFilter() {

        public void insertString(DocumentFilter.FilterBypass fb,
                                 int offset,
                                 String string,
                                 AttributeSet attr) throws BadLocationException {
            if (!isAllDigits(string))
                return;

            if (offset == 0 && string.charAt(0) == '0')
                return;

            fb.insertString(offset, string, attr);
        }


        public void replace(DocumentFilter.FilterBypass fb,
                            int offset,
                            int length,
                            String string,
                            AttributeSet attr) throws BadLocationException {
            if (!isAllDigits(string))
                return;

            if (offset == 0 && string.charAt(0) == '0')
                return;

            fb.replace(offset, length, string, attr);
        }


        private boolean isAllDigits(String string) {
            for (int i = 0; i < string.length(); i++) {
                char ch = string.charAt(i);
                if (!Character.isDigit(ch))
                    return false;
            }
            return true;
        }

    };

    private KeyListener keyListener = new KeyAdapter() {

        // has to be keyreleased otherwise getting contents is out of
        // sync
        public void keyReleased(KeyEvent e) {
            processKey();
        }
    };

    private class StrippingFocusListener extends FocusAdapter {

        private JTextField textField;


        public StrippingFocusListener(JTextField textField) {
            this.textField = textField;
        }
        
        public void focusLost(FocusEvent e) {
            String text = textField.getText();
            try {
                int number = Integer.parseInt(text);
                text = Integer.toString(number);
            }
            catch (NumberFormatException nfe) {
                // do nothing
            }
            textField.setText(text);
        }

    };


    public Runner() {
        initialiseLayout();
    }


    private void initialiseLayout() {
        setLayout(new GridBagLayout());
        GridBagConstraints c = new GridBagConstraints();

        c.fill = GridBagConstraints.BOTH;
        c.insets = new Insets(5, 5, 5, 5);

        hourFields = new JTextField [teachingMethods.length];

        for (int i = 0; i < teachingMethods.length; i++) {
            c.gridx = 0;
            c.gridy = i;
            String teachingMethod = teachingMethods[i];
            JLabel label = new JLabel(teachingMethod, SwingConstants.LEFT);
            add(label, c);

            c.gridx = 1;
            JTextField hourField = new JTextField(3);
            AbstractDocument document = (AbstractDocument) hourField.getDocument();
            document.setDocumentFilter(filter);
            hourField.addKeyListener(keyListener);
            hourField.addFocusListener(new StrippingFocusListener(hourField));
            add(hourField, c);
            hourField.setHorizontalAlignment(SwingConstants.RIGHT);
            hourFields[i] = hourField;
        }

        c.gridx = 0;
        c.gridy++;
        JLabel label = new JLabel("Current total", SwingConstants.RIGHT);
        add(label, c);

        totalLabel = new JLabel("", SwingConstants.RIGHT);
        c.gridx = 1;
        add(totalLabel, c);

        c.gridx = 0;
        c.gridy++;
        // vn
        JLabel label2 = new JLabel("Target", SwingConstants.RIGHT);
        add(label2, c);

        c.gridx = 1;
        targetLabel = new JLabel(Integer.toString(targetHours),
                                 SwingConstants.RIGHT);
        add(targetLabel, c);
    }


    /**
     * Total up.
     * 
     * 
     * 
     */
    private void processKey() {
        int totalHours = 0;
        for (JTextField hourField : hourFields) {
            try {
                int hours = Integer.parseInt(hourField.getText());
                totalHours += hours;
            }
            catch (NumberFormatException e) {
                // do nothing for now - could highlight really
            }
        }
        totalLabel.setText(Integer.toString(totalHours));
        processLabels(totalHours);
    }


    /**
     * Change colour of labels depending on whether have met target or
     * not.
     * 
     * @param totalHours
     * 
     */
    private void processLabels(int totalHours) {
        if (totalHours == targetHours) {
            totalLabel.setOpaque(true);
            targetLabel.setOpaque(true);
            totalLabel.setBackground(Color.green);
            targetLabel.setBackground(Color.green);
        }
        else {
            totalLabel.setOpaque(false);
            targetLabel.setOpaque(false);
        }
    }


    public static void main(String [] args) {
        JFrame frame = new JFrame("D4L");
        frame.setContentPane(new Runner());
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setVisible(true);
    }

}
